﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Aioms.Models;
using Furion;
using Furion.DataEncryption;
using Furion.DynamicApiController;
using Furion.UnifyResult;
using Magicodes.ExporterAndImporter.Core;
using Magicodes.ExporterAndImporter.Core.Extension;
using Magicodes.ExporterAndImporter.Excel;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OfficeOpenXml;
using SqlSugar;
using StackExchange.Profiling.Internal;

namespace Aioms.Controllers
{
    /// <summary>
    /// 设备
    /// </summary>
    [DynamicApiController]
    public class DeviceController
    {
        private readonly ISqlSugarClient db; // 核心对象：拥有完整的SqlSugar全部功能
        public DeviceController(ISqlSugarClient sqlSugarClient)
        {
            this.db = sqlSugarClient;
        }

        /// <summary>
        /// PC端-安卓端-列表
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="aeid"></param>
        /// <param name="content"></param>
        /// <param name="type"></param>
        /// <param name="status"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostList([FromForm] long eid, [FromForm] long aeid, [FromForm] string content, [FromForm] string dvtname, [FromForm] string status, [FromForm] int pageIndex = 1, [FromForm] int pageSize = 10)
        {
            RefAsync<int> total = 0;
            //List<Device> devices = await db.Queryable<Device>().Where(d => d.Eid == eid)
            //    .WhereIF(aeid != 0, d => d.Aeid == aeid)
            //    .WhereIF(!string.IsNullOrEmpty(content), d => d.Name.Contains(content))
            //    .WhereIF(!string.IsNullOrEmpty(dvtname), d => d.Dvtname == dvtname)
            //    .WhereIF(!string.IsNullOrEmpty(status), d => d.Status == status)
            //    .ToPageListAsync(pageIndex, pageSize, total);
            List<Device> devices = await db.Queryable<Device>()
                .Mapper(dv => dv.DeviceType, dv => dv.Dvtid, dv => dv.DeviceType.Id)
                .Mapper(dv => dv.Area, dv => dv.Aeid, dv => dv.Area.Id)
                .Where(d => d.Eid == eid)
                .Where(d => d.IsDel == 0)
                .WhereIF(aeid != 0, dv => dv.Aeid == aeid)
                .WhereIF(!string.IsNullOrEmpty(content), dv => dv.Name.Contains(content))
                .WhereIF(!string.IsNullOrEmpty(dvtname), dv => dv.Dvtname == dvtname)
                .WhereIF(!string.IsNullOrEmpty(status), dv => dv.Status == status)
                .ToPageListAsync(pageIndex, pageSize, total);
            UnifyContext.Fill(new { Total = total });
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = devices,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="device"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostSave([FromForm] long eid, [FromForm] Device device)
        {
            int count = await db.Queryable<Device>().Where(d => d.Eid == eid && d.Number == device.Number).CountAsync();
            if (count > 0) {
                return new JsonResult(new RESTfulResult<object>
                {
                    StatusCode = -1,
                    Succeeded = false,
                    Data = null,
                    Errors = "设备编号重复",
                    Extras = UnifyContext.Take(),
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                });
            }
            await db.Insertable<Device>(device).ExecuteCommandAsync();
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 查看
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostShow([FromForm] long eid, [FromForm] long id)
        {
            Device device = await db.Queryable<Device>().Where(d => d.Eid == eid && d.Id == id).SingleAsync();

            DeviceType devicetype = await db.Queryable<DeviceType>().Where(dt => dt.Eid == eid && dt.Id == device.Dvtid).SingleAsync();
            Area area = await db.Queryable<Area>().Where(a => a.Eid == eid && a.Id == device.Aeid).SingleAsync();
            UnifyContext.Fill(new { Area = area, DeviceType = devicetype });
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = device,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 设备更新
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="device"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostUpdate([FromForm] long eid, [FromForm] Device device)
        {
            await db.Updateable<Device>(device).ExecuteCommandAsync();
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = device,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostDelete([FromForm] long eid, [FromForm] long id)
        {
            await db.Updateable<Device>().SetColumns(d => d.IsDel == 1).Where(d => d.Eid == eid && d.Id == id).ExecuteCommandAsync();
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 下载模板
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> PostDownloadexceltemplate()
        {
            //IExcelExporter exporter = new ExcelExporter();
            //var filePath = @"wwwroot/download/baoxiu/设备模板.xlsx";
            //var arr = new[] { "设备名称", "设备编号", "规格型号", "购置日期", "生产厂商", "供应商", "描述" };
            //var sheetName = "设备";
            //var result = await exporter.ExportHeaderAsByteArray(arr, sheetName);
            //result.ToExcelExportFileInfo(filePath);
            JObject data = new();
            data.Add("url", $"http://{App.HttpContext.Request.Host.Value}/download/baoxiu/设备模板.xlsx");
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = data,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> PostExportexcel([FromForm] long eid)
        {
            IExporter exporter = new ExcelExporter();
            await exporter.Export(@"wwwroot/download/baoxiu/设备.xlsx", await db.Queryable<Device>().Where(d => d.Eid == eid).Where(d => d.IsDel == 0).ToListAsync());

            JObject data = new();
            data.Add("url", $"http://{App.HttpContext.Request.Host.Value}/download/baoxiu/设备.xlsx");
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = data,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostImportexcel([FromForm] long eid, [FromForm] long aeid, [FromForm] string aename, [FromForm] string filePath)
        {
            //filePath = @"upload/excel/设备模板.xlsx";
            string webrootpath = App.WebHostEnvironment.WebRootPath;
            FileInfo file = new(Path.Combine(webrootpath, filePath));

            long affrows = 0;
            try
            {
                using (ExcelPackage package = new(file))
                {
                    ExcelWorksheet worksheet = package.Workbook.Worksheets.First();
                    int rowCount = worksheet.Dimension.Rows;
                    var items = new List<Device>();
                    for (int row = 2; row <= rowCount; row++)
                    {
                        items.Add(new Device { Eid = eid, Aeid = aeid, Aename = aename, Dvtid = -1, Dvtname = "", Name = worksheet.Cells[row, 1].Value?.ToString() ?? "", Number = worksheet.Cells[row, 2].Value?.ToString() ?? "", Specification = worksheet.Cells[row, 3].Value?.ToString() ?? "", Position = "", PurchaseDate = worksheet.Cells[row, 4].GetValue<DateTime>(), Manufacturer = worksheet.Cells[row, 5].Value?.ToString() ?? "", Provider = worksheet.Cells[row, 6].Value?.ToString() ?? "", Model = "", Description = worksheet.Cells[row, 7].Value?.ToString() ?? "", Cover = "", Status = "正常"});
                    }
                    affrows = await db.Insertable(items).ExecuteCommandAsync();
                }
            }
            catch (Exception e)
            {
                affrows = -1;
                Console.WriteLine("导入设备失败：" + e.Message);
            }

            if (affrows == -1)
            {
                return new JsonResult(new RESTfulResult<object>
                {
                    StatusCode = -1,
                    Succeeded = true,
                    Data = false,
                    Errors = null,
                    Extras = UnifyContext.Take(),
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                });
            }
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }
    }
}
